// Package main provides the main entry point for the smart snapshotter
package main

import (
	"context"
	"log"
	"os"
	"os/signal"
	"syscall"

	"github.com/smart-snapshotter/internal/config"
	"github.com/smart-snapshotter/internal/errors"
	"github.com/smart-snapshotter/internal/logging"
	"github.com/smart-snapshotter/internal/metrics"
	"github.com/smart-snapshotter/pkg/snapshotter"
)

func main() {
	// Initialize logging
	if err := logging.InitGlobalLogger(nil); err != nil {
		log.Fatalf("Failed to initialize logging: %v", err)
	}
	defer logging.Sync()

	// Initialize error handling
	errors.InitGlobalErrorManager()

	// Load configuration
	cfg, err := config.Load()
	if err != nil {
		logging.Fatalf("Failed to load configuration", logging.ErrorField(err))
	}

	// Initialize metrics
	if err := metrics.InitGlobalMetrics(&cfg.Metrics); err != nil {
		logging.Fatalf("Failed to initialize metrics", logging.ErrorField(err))
	}

	// Create root directory
	root := "./data/smart-snapshotter"
	if err := os.MkdirAll(root, 0755); err != nil {
		logging.Fatalf("Failed to create root directory", logging.ErrorField(err))
	}

	// Create snapshotter
	ctx := context.Background()
	snap, err := snapshotter.New(ctx, root, cfg)
	if err != nil {
		logging.Fatalf("Failed to create snapshotter", logging.ErrorField(err))
	}
	defer func() {
		if err := snap.Close(); err != nil {
			logging.Errorf("Failed to close snapshotter", logging.ErrorField(err))
		}
	}()

	// Register snapshotter with containerd
	// This would normally be done through containerd's plugin system
	logging.Info("Smart snapshotter initialized successfully",
		logging.StringField("storage_type", cfg.Storage.Type),
		logging.StringField("dedup_algorithm", cfg.Dedup.Algorithm),
		logging.BoolField("dedup_enabled", cfg.Dedup.Enabled),
		logging.StringField("cache_type", cfg.Cache.Type))

	// Setup signal handling
	sigChan := make(chan os.Signal, 1)
	signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)

	// Wait for shutdown signal
	<-sigChan
	logging.Info("Shutting down smart snapshotter...")
}